import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws SQLException {
        //0.让用户自己输入id,name
        Scanner sca = new Scanner(System.in);
        System.out.println("请输入用户Id");
        int id = sca.nextInt();
        System.out.println("请输入用户姓名");
        String name = sca.next();
        //1.创建数据源对象
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java112?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("8867993");

        //2.和数据库服务建立网路连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

        //3.构造sql语句
        //构造方式有很多种，
        //PreparedStatement 基于这个类，构造sql

        //String sql = "insert into st values("+ id + ",'"+name+"')";
        String sql = "insert into st values (?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id);
        statement.setString(2,name);

        //4.把sql发送到服务器上执行
        //返回值是这个sql影响到几行
        int i = statement.executeUpdate();

        /*String sql2 = "select name,class_id from student where name = '许仙'";
        PreparedStatement statement = connection.prepareStatement(sql2);
        ResultSet resultSet = statement.executeQuery();*/




        //5.释放上述资源
        statement.close();
        connection.close();

    }
}